<template>
  <div class="nav-menu">
    <div class="logo">
      <router-link to="/">
        <img src="~assets/image/monkey.png" alt="logo" />
      </router-link>
      <h3 v-if="!isCollapse" class="title">后台管理系统</h3>
    </div>
    <el-menu
      class="el-menu-vertical"
      :default-active="activeMenuId"
      background-color="#0c2135"
      text-color="#eee"
      active-text-color="#eee"
      :collapse="isCollapse"
      :collapse-transition="false"
    >
      <template v-for="(menu, index) in userMenus" :key="menu.id">
        <!-- 二级标题 -->
        <template v-if="menu.type === 1">
          <el-sub-menu :index="menu.id + ''">
            <template #title>
              <el-icon v-if="menu.icon">
                <component :is="iconCpns[index].name"></component>
              </el-icon>
              <span>{{ menu.name }}</span>
            </template>
            <el-menu-item
              v-for="menuItem in menu.children"
              :key="menuItem.id"
              :index="menuItem.id + ''"
              @click="menuClick(menuItem)"
            >
              <span>{{ menuItem.name }}</span>
            </el-menu-item>
          </el-sub-menu>
        </template>
        <!-- 一级标题 -->
        <template v-else-if="menu.type === 2">
          <el-menu-item :index="menu.id + ''">
            <span>{{ menu.name }}</span>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useStore } from '@/store'
import { Monitor, Setting, Goods, PieChart } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { mapPathToMenu } from '@/utils/map-menus'

export default defineComponent({
  props: ['isCollapse'],
  components: {
    Monitor,
    Setting,
    Goods,
    PieChart
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    const userMenus = store.state.login.userMenus
    const iconCpns = [Monitor, Setting, Goods, PieChart]
    const currentMenu = mapPathToMenu(userMenus, route.path)
    const activeMenuId = ref(currentMenu?.id + '')

    const menuClick = (menuItem: any) => {
      router.push(menuItem.url)
    }

    return {
      userMenus,
      iconCpns,
      activeMenuId,
      menuClick
    }
  }
})
</script>

<style lang="less" scoped>
.nav-menu {
  .logo {
    margin-top: 20px;
    color: #eee;
    img {
      height: 56px;
      object-fit: contain;
      border-radius: 50%;
      background-color: #eee;
      box-shadow: 0 0 6px #eee;
    }
    .title {
      line-height: 0;
    }
  }
}

.el-menu {
  border-right: none;
}

.el-menu-item.is-active {
  background-color: #147be3;
}

.el-menu-item:hover {
  background-color: #147be3;
  opacity: 0.9;
}
</style>
